#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/1 22:03
# @Author : 闫峰
# @File    : set_amazon_sales_ban_es.py


import os
import threading
import time

import requests

from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.sql_server_utils import MSSQL
from concurrent.futures import ThreadPoolExecutor
from functools import partial

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class Set_amazon_sales_ban:
    db = MSSQL(ensure_path_sep("\\config\\config.yaml"), "sqlserver_db_erp_base")
    insert_db = Database(ensure_path_sep("\\config\\ceshi_mysql_config.yaml"), "log_db")

    def set_amazon_sales_ban(self):

        sql = """
        SELECT distinct sku FROM znkdceshilog.set_amazon_sales_ban_copy1_copy1
        """
        # offset = 160073124
        # batch_size = 1000
        res1 = self.insert_db.fetch_all_tuple(sql, ())
        set1 = set(map(lambda x: x[0], res1))
        sql2 = """
        SELECT distinct sku FROM znkdceshilog.set_amazon_sales_ban_copy1
        """
        res2 = self.insert_db.fetch_all_tuple(sql2, ())
        set2 = set(map(lambda x: x[0], res2))
        intersection = set1 & set2
        print()
        if set1 == set2:
            pass
        else:
            print(set1 - set2)
            print(len(set1 - set2))
            print(set2 - set1)
            print(len(set2 - set1))
            print()

    @staticmethod
    def handler(id_interval):
        db = MSSQL(ensure_path_sep("\\config\\config.yaml"), "sqlserver_db_erp_base")
        insert_db = Database(ensure_path_sep("\\config\\ceshi_mysql_config.yaml"), "log_db")

        sql2 = """
        SELECT top 1000 sku FROM [dbo].[RB_Product] WHERE id >= %s AND id <= %s
        """
        res2 = db.ExecQuery(sql2, (id_interval[0], id_interval[1]))
        sku_list = list(map(lambda x: x[0], res2))
        new_lst = ["'" + x + "'" for x in sku_list]
        new_s = ",".join(new_lst)
        # for sku in sku_list:
        headers = {
            "Authorization": "Basic aXJvYm90Ym94OmkxcjVvOEJvdGJveA=="
        }
        url = "http://erplog.zhcxkj.com/api/systems/logs/List"
        json_data = {
            "input": {
                "tableName": "RB_Product_Log_1",
                "equal": [
                    {
                        "fieldName": "CustomerID",
                        "value": "1",
                        "dataType": 1
                    }
                ],
                "ins": [{
                    "fieldName": "SKU",
                    "value": new_s,
                    "dataType": 1
                }],
                "likes": [
                    {
                        "fieldName": "OperationTxt",
                        "value": "服务自动设置亚马逊禁售国家：沙特阿拉伯,阿拉伯联合酋长国",
                        "dataType": 3
                    }
                ],
                "ranges": [
                    {
                        "fieldName": "AddTime",
                        "dataType": 2,
                        "beginValueGX": "gt",
                        "beginValue": "2023-07-06",
                        "endValueGX": "lt",
                        "endValue": "2023-09-01"
                    }
                ],
                "orderBy": [
                    {
                        "fieldName": "AddTime",
                        "value": "-1",
                        "dataType": 0
                    }
                ],
                "current": 1,
                "pageSize": 2000
            }
        }

        res3 = requests.post(url=url, json=json_data, headers=headers).json()
        if res3.get('data'):
            res4 = res3.get('data').get('dataSource')
            data_list = list(
                map(lambda data: (data.get('id'), data.get('sku'), data.get('operationtxt'), data.get('addtime')),
                    res4))
            # 插入数据库
            insert_sql = """
            INSERT IGNORE INTO znkdceshilog.set_amazon_sales_ban_copy1 (erp_id, sku, text,addtime)
            VALUES (%s, %s, %s,%s);
            """
            row1 = insert_db.execute_many(insert_sql, data_list)
            if row1 == 0:
                ERROR.logger.error(f"""
            INSERT IGNORE INTO znkdceshilog.set_amazon_sales_ban_copy1 (erp_id, sku, text,addtime)
            VALUES (%s, %s, %s,%s);
            插入失败
            data_list={data_list}
                """)
        INFO.logger.info(f"thread_id={threading.current_thread().ident} \n "
                         f"执行完了id_interval={id_interval}")


if __name__ == '__main__':
    # Set_amazon_sales_ban().set_amazon_sales_ban()
    #
    t = Set_amazon_sales_ban()
    t.set_amazon_sales_ban()
